﻿using ECommon;
using LeanApp.Common;
using LeanApp.View;
using System;
using System.IO;

namespace LeanApp.Bll
{
    /// <summary>
    /// 注册业务逻辑
    /// </summary>
    public class RegisterBll
    {
        /// <summary>
        /// 验证当前设备是否注册
        /// </summary>
        /// <returns>验证结果</returns>
        public bool IsRegister()
        {
            bool res = false;
            if (File.Exists(_lsnFilePath))
            {
                string lsnTxt = FileTool.Read(_lsnFilePath);
                string decodeLsnTxt = EncryptTool.TripleDESDecrypt(HardwareTool._userKey, lsnTxt);
                res = UserInfo == decodeLsnTxt;
            }
            return res;
        }

        /// <summary>
        /// 执行注册程序
        /// </summary>
        /// <returns>注册结果</returns>
        public bool RunRegister()
        {
            bool res = false;
            RegisterWindow rw = new RegisterWindow(UserInfo);
            bool? windowResult = rw.ShowDialog();
            if (windowResult == true)
            {
                WriteRegisterInfo();
                res = true;
            }
            return res;
        }

        /// <summary>
        /// 写入注册信息
        /// </summary>
        public void WriteRegisterInfo()
        {
            string encodeLsnTxt = EncryptTool.TripleDESEncrypt(HardwareTool._userKey, UserInfo);
            FileTool.Write(encodeLsnTxt, _lsnFilePath);
        }

        /// <summary>
        /// 用户信息
        /// </summary>
        private string _userInfo = "";

        /// <summary>
        /// 用户信息，私有只读属性
        /// </summary>
        private string UserInfo
        {
            get
            {
                if (string.IsNullOrWhiteSpace(_userInfo))
                {
                    string cpuId = HardwareTool.GetCpuId();
                    string macAddress = HardwareTool.GetMacAddress();
                    _userInfo = "CPU：" + cpuId + "，MAC：" + macAddress;
                }
                return _userInfo;
            }
        }

        /// <summary>
        /// 注册文件路径
        /// </summary>
        private string _lsnFilePath = AppDomain.CurrentDomain.BaseDirectory + "Lsn\\reg.lsn";
    }
}
